import random

from django.http import HttpResponse
from django.shortcuts import render

# Create your views here.
from django_redis import get_redis_connection
from rest_framework.response import Response
from rest_framework.views import APIView

from libs.captcha.captcha import captcha
from verifications.serializers import RegisterSmscodeSerializer

"""
生成图片验证码
GET verifications/imagecodes/(?P<image_code_id>.+)/

前端传递一个uuid过来，我们后端生成一个图片
１接受image_code_id
2生成图片和验证码
３吧验证码保存到redis
4返回图片响应
"""

class RegisterImageAPIView(APIView):
    def get(self,request,image_code_id):
        text,image = captcha.generate_captcha()
        redis_conn = get_redis_connection('code')
        redis_conn.setex('img_'+image_code_id,60,text)
        # 图片是二进制的我们通过HttpResponse返回
        return HttpResponse(image,content_type='image/jpeg')

"""
短信验证码　当用户点击获取短信按钮的时候，前段应该将手机号，图片验证码及验证码ｉｄ发送给后端
1.接收参数
2.校验参数
3.生成短信
4.将短信保存在redis中
5.使用云通讯发送短信
6.返回相应

GET             /verifications/smscodes/(?P<mobile>1[345789]\d{9})/?text=xxxx & image_code_id=xxxx
"""

class RegisterSmscodeAPIView(APIView):
    def get(self,request,mobile):
        # 1.接收参数
        params = request.query_params
        # 2.校验参数
        serializer =RegisterSmscodeSerializer(data=params)
        serializer.is_valid(raise_exception=True)
        # 3.生成短信
        sms_code = '%06d'%random.randint(0,999999)
        # 4.将短信保存在redis中 线链接redis
        redis_conn = get_redis_connection('code')
        redis_conn.setex('sms_'+mobile,5*60,sms_code)
        # 5.使用云通讯发送短信
        from celery_tasks.sms.tasks import send_sms_code
        # delay的参数和任务的参数对应　　必须调用delay方法
        send_sms_code.delay(mobile,sms_code)
        # 6.返回相应
        return Response({'msg':'ok'})